package com.momo.hotel.controller;

import com.momo.hotel.dao.pojo.TbNews;
import com.momo.hotel.dao.pojo.TbUser;
import com.momo.hotel.dao.pojo.ext.TbNewsExt;
import com.momo.hotel.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;

/**
 * @author qiang
 * @create 2019/7/5
 */
@Controller
public class NewsController {

    @Autowired
    NewsService newsService;

    static String UPLOAD_PATH = "/upload/";
    static String PIC;

    @ResponseBody
    @RequestMapping(value = "wangEditor", method = RequestMethod.POST)
    public Map<String, Object> upload1(MultipartFile editorFile, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>();

        // 获取文件后缀
        String fileName = editorFile.getOriginalFilename();
        String fileSuffix = fileName.substring(fileName.lastIndexOf("."));

        // 文件存放路径
        String filePath = request.getSession().getServletContext().getRealPath(UPLOAD_PATH);
        InetAddress ia = null;
        try {
            ia = ia.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        // 判断路径是否存在，不存在则创建文件夹
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdir();
        }

        // 将文件写入目标
        file = new File(filePath, UUID.randomUUID() + fileSuffix);
        try {
            editorFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 获取服务端路径
        String serverPath = String.format("%s://%s:%s%s%s", request.getScheme(), ia.getHostAddress(), request.getServerPort(), request.getContextPath(), UPLOAD_PATH);
        // 返回给 wangEditor 的数据格式
        result.put("errno", 0);
        result.put("data", new String[]{serverPath + file.getName()});
        PIC = file.getName();
        return result;
    }

    /**
     * 添加新闻
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("addNews")
    public void addNews(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        TbUser user = (TbUser) request.getSession().getAttribute("user");
        if (user != null) {
            if (user.getMember() == 1) {
                TbNews tbNews = new TbNews();
                //用户编号
                Integer userId = user.getId();
                //新闻标题
                String title = request.getParameter("title");
                //新闻内容
                String content = request.getParameter("content");
                //新闻图片 PIC
                //发布时间 new Date()
                tbNews.setUserid(userId);
                tbNews.setTitel(title);
                tbNews.setContent(content);
                if(PIC==null){
                    tbNews.setPic("default.jpg");
                }else {
                    tbNews.setPic(PIC);
                }
                System.out.println(PIC+"##################@");
                tbNews.setTime(new Date());
                if (title != "") {
                    if (!content.equals("<p><br></p>")) {
                        Integer integer = newsService.addNews(tbNews);
                        if (integer != 0) {
                            response.getWriter().write("发布成功");
                        } else {
                            response.getWriter().write("发布失败");
                        }
                    } else {
                        response.getWriter().write("内容不能为空");
                    }
                } else {
                    response.getWriter().write("标题不能为空");
                }
            } else {
                response.getWriter().write("您不是会员,不能发布新闻,请充值！");
            }
        } else {
            response.getWriter().write("请登录");
        }
    }

    /**
     * 查询新闻
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("selectNews")
    public Object selectNews() {
        List<TbNewsExt> tbNewsExts = newsService.selectNews();
        System.out.println(tbNewsExts.toString());
        return tbNewsExts;
    }


    /**
     * 获取新闻详情的id，并setSession
     *
     * @param request
     * @return
     */
    @RequestMapping("newsDetail")
    public String newsDetail(HttpServletRequest request) {
        String id = request.getParameter("id");
        TbNewsExt tbNewsExt = newsService.newsDetail(Integer.parseInt(id));
        request.getSession().setAttribute("tbNewsExt", tbNewsExt);
        //跳转页面
        return "news-detail";
    }

    /**
     * 根据getSession获取新闻详情
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("newsDetail1")
    public Object newsDetail1(HttpServletRequest request) {
        TbNewsExt tbNewsExt = (TbNewsExt) request.getSession().getAttribute("tbNewsExt");
        return tbNewsExt;
    }


    /**
     * 查询新闻有限
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("selectNewsLimit")
    public Object selectNewsLimit() {
        List<TbNewsExt> tbNewsExts = newsService.selectNewsLimit();
        return tbNewsExts;
    }
}